package org.dut.community.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dut.community.annotation.LoginRequired;
import org.dut.community.entity.Comment;
import org.dut.community.entity.DiscussPost;
import org.dut.community.entity.Page;
import org.dut.community.entity.User;
import org.dut.community.service.*;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.HostHolder;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    @Value("${Community.path.upload}")
    private String uploadPath;
    @Value("${Community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private RedisTemplate redisTemplate;

//    @LoginRequired
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getSettingPage() {
        return "/site/setting";
    }

//    @LoginRequired
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error","上传头像图片为空!");
            return "/site/setting";
        }
        // 1.给头像图片一个唯一的文件名
        String fileName = headerImage.getOriginalFilename();
        // 提取文件后缀，不改变文件格式
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式错误!");
            return "/site/setting";
        }
        fileName = CommunityUtil.getUUID() + suffix;

        // 2.存储文件
        File dist = new File(uploadPath + "/" + fileName);
        try {
            headerImage.transferTo(dist);
        } catch (Exception e) {
            log.error("上传文件失败:" + e.getMessage());
            throw new RuntimeException("上传文件失败",e);
        }

        // 3. 更新数据库
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        int rows = userService.updateHeader(user.getId(),headerUrl);
        if(rows == 0){
            model.addAttribute("error","头像更新失败!");
            return "/site/setting";
        }

        // 4. 刷新用户
        hostHolder.setUser(userService.findUserById(user.getId()));
        model.addAttribute("message","头像更新成功!");
        return "redirect:/index";
    }

    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀，不包含.
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (Exception e) {
            log.error("读取头像失败:" + e.getMessage());
        }
    }

    // 更改密码
//    @LoginRequired
    @RequestMapping(path = "/updatePassword",method = RequestMethod.POST)
    public String updatePassword(String oldPassword,String newPassword1,String newPassword2,Model model){
        User user = hostHolder.getUser();
        Map<String,Object> map = userService.updatePassword(user.getId(),oldPassword,newPassword1,newPassword2);
        if(map.isEmpty()){
            model.addAttribute("message","密码更新成功!");
            return "redirect:/index";
        } else {
            model.addAttribute("oldPasswordMsg",map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg",map.get("newPasswordMsg"));
            return "/site/setting";
        }
    }

    // 个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在！");
        }
        // 用户
        model.addAttribute("user", user);
        // 获赞
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);
        // 关注了
        long followeeCount = followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 是否关注
        boolean hasFollowed = false;
        if(hostHolder.getUser() != null){
            hasFollowed = followService.isFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }

    // 我的帖子
    @RequestMapping(path = "/mypost/{userId}", method = RequestMethod.GET)
    public String getMyPost(@PathVariable("userId") int userId, Page page, Model model,
                            @RequestParam(name = "orderMode",defaultValue = "1")int orderMode) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);

        // 分页信息
        page.setLimit(10);
        page.setPath("/user/mypost/" + userId);
        page.setRows(discussPostService.selectDiscussPostRows(userId));

        // 帖子列表
        List<DiscussPost> discussList = discussPostService
                .selectDiscussPosts(userId, page.getOffset(), page.getLimit(),orderMode);
        List<Map<String, Object>> discussVOList = new ArrayList<>();
        if (discussList != null) {
            for (DiscussPost post : discussList) {
                Map<String, Object> map = new HashMap<>();
                map.put("discussPost", post);
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
                // 阅读量
                String redisKey = RedisKeyUtil.getPostReadKey(post.getId());
                map.put("postReadCount",redisTemplate.opsForValue().get(redisKey) == null ? 0 : redisTemplate.opsForValue().get(redisKey));
                discussVOList.add(map);
            }
        }
        model.addAttribute("discussPosts", discussVOList);

        return "/site/my-post";
    }

    //我的回复
    @RequestMapping(path = "/myreply/{userId}", method = RequestMethod.GET)
    public String getMyReply(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);

        // 分页信息
        page.setLimit(10);
        page.setPath("/user/myreply/" + userId);
        page.setRows(commentService.findUserCount(userId));

        // 评论列表
        List<Comment> commentList = commentService.findUserComments(userId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> commentVOList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                map.put("discussPost", post);
                // 阅读量
                String redisKey = RedisKeyUtil.getPostReadKey(post.getId());
                map.put("postReadCount",redisTemplate.opsForValue().get(redisKey)==null?0:redisTemplate.opsForValue().get(redisKey));
                commentVOList.add(map);
            }
        }
        model.addAttribute("comments", commentVOList);

        return "/site/my-reply";
    }

    // 我赞过的帖子
    @RequestMapping(path = "/mylikes/{userId}", method = RequestMethod.GET)
    public String getMyLikes(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);

        List<DiscussPost> discussList = likeService.findUserLikePosts(userId);
        // 分页信息
        page.setLimit(10);
        page.setPath("/user/mylikes/" + userId);
        page.setRows(discussList.size());

        List<Map<String, Object>> discussVOList = new ArrayList<>();
        if (!discussList.isEmpty()) {
            for (DiscussPost post : discussList) {
                Map<String, Object> map = new HashMap<>();
                map.put("discussPost", post);
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
                // 阅读量
                String redisKey = RedisKeyUtil.getPostReadKey(post.getId());
                map.put("postReadCount",redisTemplate.opsForValue().get(redisKey)==null?0:redisTemplate.opsForValue().get(redisKey));
                discussVOList.add(map);
            }
        }
        model.addAttribute("discussPosts", discussVOList);

        return "/site/my-likes";
    }


}
